package com.xz.util;

import com.xz.bean.Source;
import org.apache.commons.lang.StringUtils;
import org.codehaus.jackson.map.ObjectMapper;

import java.io.*;

/**
 * Created by YLZX-Z0107 on 2014/8/26.
 */
public class EndIdUtil {
    private static String path = null;
    private static ObjectMapper objectMapper = new ObjectMapper();

    public static Source getStart() {
        String json = getStartId();
        if (StringUtils.isEmpty(json)) {
            try {
                json = objectMapper.writeValueAsString(new Source(0));
                writeStartId(json);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        Source source = null;
        try {
            source = objectMapper.readValue(json, Source.class);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return source;
    }

    public static void writeStart(Source source) {
        if (source != null) {
            try {
                String json = objectMapper.writeValueAsString(source);
                writeStartId(json);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static void writeStartId(String source) {
        if (path == null || path.length() < 1) {
            path = System.getProperty("user.dir");
        }
        try {
            File file = new File(path + File.separator + "conf" + File.separator + "recruit.txt");
            if (!file.exists())
                file.createNewFile();
            FileWriter fw = new FileWriter(file);
            fw.write(source);
            fw.flush();
            fw.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static String getStartId() {
        if (path == null || path.length() < 1) {
            path = System.getProperty("user.dir");
        }
        String result = "";
        try {
            File file = new File(path + File.separator + "conf" + File.separator + "recruit.txt");
            if (!file.exists())
                file.createNewFile();
            FileReader fr = new FileReader(file);
            BufferedReader br = new BufferedReader(fr);
            String s;
            while ((s = br.readLine()) != null) {
                result += s;
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }
}
